import Mn from 'backbone.marionette';
import InputWidget from '../../../../../widgets/InputWidget.js';
import SelectWidget from '../../../../../widgets/SelectWidget.js';
import TextAreaWidget from '../../../../../widgets/TextAreaWidget.js';
import FormBehavior from '../../../../../base/behaviors/FormBehavior.js';
import Radio from 'backbone.radio';
var template = require('./templates/DiscountFormView.mustache');

const DiscountFormView = Mn.View.extend({
    tagName: 'div',
    className: 'modal_overflow',
    behaviors: [FormBehavior],
    template: template,
    regions: {
        'order': '.order',
        'description': '.description',
        'amount': '.amount',
        'tva': '.tva',
    },
    childViewTriggers: {
        'change': 'data:modified',
    },
    initialize() {
        const config = Radio.channel('config');
        const tva_options = config.request('get:options', 'tvas');
        this.compute_mode = config.request('get:options', 'compute_mode');
        // Only allow discounts on existing tva types
        let facade = Radio.channel('facade');
        let total_model = facade.request('get:model', 'total');
        let used_tvas = total_model.tva_values();
        this.tva_options = tva_options.filter(tva => used_tvas.indexOf(tva.value) != -1);
    },
    onRender: function () {
        let label;
        this.showChildView(
            'order',
            new InputWidget({
                value: this.model.get('order'),
                field_name: 'order',
                type: 'hidden',
            })
        );
        this.showChildView(
            'description',
            new TextAreaWidget({
                value: this.model.get('description'),
                title: "Description",
                field_name: "description",
                tinymce: true,
                cid: this.model.cid,
                required: true,
            })
        );

        if (this.compute_mode == 'ttc') {
            label = "Montant TTC";
        } else {
            label = "Montant HT"
        }
        this.showChildView(
            'amount',
            new InputWidget({
                value: this.model.get('amount'),
                label: label,
                field_name: "amount",
                required: true,
            })
        );
        this.showChildView(
            'tva',
            new SelectWidget({
                options: this.tva_options,
                title: "TVA",
                value: this.model.get('tva'),
                id_key: 'value',
                field_name: 'tva',
                required: true,
            })
        );
    },
    templateContext: function () {
        return {
            title: this.getOption('title'),
        };
    }
});
export default DiscountFormView;